#include "ByteArray.h"
#include <string>
#include <stdio.h>
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;

ByteArray::ByteArray()
{
    //ctor
}

//public
bool ByteArray::readBytesFromFile(const char *fileName){
    // open the file
	ifstream file;
	file.open(fileName, ios::binary);

	if(!file.is_open()){
		cout<<"Error File";
		return false;
	}

	// get the length of the file
	file.seekg(0, ios::end);
	fileSize = file.tellg();
	file.seekg(0, ios::beg);
	data.reserve(fileSize);

	// read the file and put it in a vector
	file.read(&data[0], fileSize);
	position = 0;
	return true;
}

void ByteArray::setPosition(int value){
    position = value;
}

int ByteArray::readInt()
{
    //cout<<position<<" readInt "<<fileSize<<endl;
    int output;

    *((char*)(&output) + 3) = data[position++];
    *((char*)(&output) + 2) = data[position++];
    *((char*)(&output) + 1) = data[position++];
    *((char*)(&output) + 0) = data[position++];

    return output;
}

unsigned int ByteArray::readUnsignedInt()
{
    //cout<<position<<" readUnsignedInt "<<fileSize<<endl;
    unsigned int output;

    *((char*)(&output) + 3) = data[position++];
    *((char*)(&output) + 2) = data[position++];
    *((char*)(&output) + 1) = data[position++];
    *((char*)(&output) + 0) = data[position++];

    return output;
}

float ByteArray::readFloat()
{
    //cout<<position<<" readFloat "<<fileSize<<endl;
    float output;

    *((char*)(&output) + 3) = data[position++];
    *((char*)(&output) + 2) = data[position++];
    *((char*)(&output) + 1) = data[position++];
    *((char*)(&output) + 0) = data[position++];

    return output;
}

short ByteArray::readShort()
{
    //cout<<position<<" readShort "<<fileSize<<endl;
    short output;

    *((char*)(&output) + 1) = data[position++];
    *((char*)(&output) + 0) = data[position++];

    return output;
}

int ByteArray::readByte()
{
    //cout<<position<<" readByte "<<fileSize<<endl;
    int output = data[position++];
    return output;
}

unsigned int ByteArray::readUnsignedByte()
{
    //cout<<position<<" readUnsignedByte "<<fileSize<<endl;
    unsigned int output = data[position++];
    return output;
}

bool ByteArray::readBoolean()
{
    //cout<<position<<" readBoolean "<<fileSize<<endl;
    if(data[position++]==0){
        return false;
    }
    return true;
}

bool ByteArray::isFinished()
{
    if(position>=fileSize){
        return true;
    }

    return false;
}
